function TimeDate(type) {
	let now = new Date(),
		val = ''

	function nine(val) {
		return val > 9 ? val : '0' + val
	}

	var year = String(now.getFullYear());
	var month = String(nine(now.getMonth() + 1));
	var date = String(nine(now.getDate()));
	var hour = String(nine(now.getHours()));
	var minute = String(nine(now.getMinutes()));
	var second = String(nine(now.getSeconds()));
	if (type == 2) {
		val = hour + minute + second;
	} else {
		val = year + month + date + hour + minute + second;
	}
	return val
}

function zeroPadd(date) {
	var hours = date.getHours(); // 获取时
	var minutes = date.getMinutes(); // 获取分
	var seperator1 = "-"; // 自定义日期分隔符
	var year = date.getFullYear(); // 获取年
	var month = date.getMonth() + 1; // 获取月
	var strDate = date.getDate(); // 获取日

	if (month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if (strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	if (hours >= 0 && hours <= 9) {
		hours = "0" + hours;
	}
	if (minutes >= 0 && minutes <= 9) {
		minutes = "0" + minutes;
	}

	var time = hours + ":" + minutes + ":" + '00'; // 时分
	var currentdate = year + seperator1 + month + seperator1 + strDate; // 年月日
	var date = currentdate + ' ' + time

	return date;
}

function setTable(arr) {
	let val = ''
	if (arr && arr.length) {
		arr.map(item => {
			val += `<tr>
                 <td class="name">${item.name}</td>
                 <td>${item.siteName}</td>
                 <!--<td>${item.operation}</td>-->
                 <!--<td>${item.nextStation}</td>-->
                 <td class="btn-span">
                      <span class="edit">编辑</span>
                      <span class="del">删除</span>
                 </td>
                 </tr>
            `
		})
	}

	$('.popup-work-station .table-main').html(val)
}

function orderCode() {
	var code = '';
	for (var i = 0; i < 6; i++) //6位随机数，用以加在时间戳后面。
	{
		code += Math.floor(Math.random() * 10);
	}
	return code = TimeDate() + code; //时间戳，用来生成订单号。
}

function accessTimeInAnHour() {
	var date = new Date();
	var date1 = new Date().getTime(); // 获取当前时间戳
	// 当前时间戳+3600s（一小时，其他时间通过计算时间戳进行相应加减），重新设置 Date 对象
	date.setTime(date1 + 3600000);
	return this.zeroPadd(date);
}

function setWorkInfo(arr, plateNumber) {
	let val = '',
		info = '',
		span = ''
	if (arr && arr.length) {
		arr.map(item => {
			if (item.plateNumber) {
				info = '已绑定其他'
				span = ''
				if (item.plateNumber === plateNumber) {
					info = '已绑定当前'
					span = ` <span class="binding unbind">解绑</span>`
				}
			} else {
				info = '暂无绑定';
				span = ` <span class="binding">绑定</span>`
			}
			val += `<tr>
                 <td class="name">${item.name}</td>
                 <td>${info}</td>
                 <td class="btn-span">
                     ${span}
                 </td>
                 </tr>
            `
		})
	}

	$('.popup-work-info .table-main').html(val)
}

function getRack(arr) {
	let val = '',
		info = '',
		span = ` `
	if (arr && arr.length) {
		arr.map(item => {
			val += `
                <tr>
                 <td class="name">${item.serialNumber}</td>
                 <td>${item.locationName}</td>
                 <td>${item.coordinates_x}</td>
                 <td>${item.coordinates_y}</td>
                <td class="btn-span">
                      <span class="edit">编辑</span>
                      <span class="del">删除</span>
                 </td>
                 </tr>
            `
		})
	}
	$('.popup-rack-info .table-main').html(val)
}

function setVehicleInfo(arr, workstation) {
	let val = '',
		info = '',
		span = ` `,
		hasType = -1
	if (arr && arr.length) {
		let valArr = []
		arr.map(item => {
			if (workstation === item.allowedOrderTypes[0]) {
				valArr.push(true)
			} else {
				valArr.push(false)
			}
		})
		hasType = valArr.indexOf(true)
		if (hasType > -1) {
			arr.map(item => {
				if (item.allowedOrderTypes && item.allowedOrderTypes.length) {
					if (item.allowedOrderTypes[0] === "*") {
						info = '暂无绑定'
						span = ``
					} else {
						info = '绑定' + item.allowedOrderTypes[0] + '工站'
						span = ''
						if (workstation === item.allowedOrderTypes[0]) {
							info = '已绑定当前工站'
							span = ` <span class="binding unbind">解绑</span>`
						} else {
							// span=''
						}
					}
				}
				val += `<tr>
                 <td class="name">${item.name}</td>
                 <td>${item.energyLevel}%</td>
                 <td>${info}</td>
                 <td class="btn-span">
                     ${span}
                 </td>
                 </tr>
            `
			})
		} else {
			arr.map(item => {
				if (item.allowedOrderTypes && item.allowedOrderTypes.length) {
					if (item.allowedOrderTypes[0] === "*") {
						info = '暂无绑定'
						span = ` <span class="binding">绑定</span>`
					} else {
						info =item.allowedOrderTypes[0]
						span = ''

					}
				}
				val += `<tr>
                 <td class="name">${item.name}</td>
                 <td>${item.energyLevel}%</td>
                 <td>${info}</td>
                 <td class="btn-span">
                     ${span}
                 </td>
                 </tr>
            `
			})
		}
	}
	$('.popup-vehicle-info .table-main').html(val)
}

function setWiFiInfo(arr, currentWifi) {
	let val = '',
		info = '',
		span = ` `,
		hasType = -1
	if (arr && arr.length) {
		arr.map(item => {
			if (item == currentWifi) {
				val += `<tr>
				    <td class="name">${item}</td>
				    <td class="btn-span">
				          <span class="edit">修改密码</span>
				     </td>
				     </tr>
				`
			} else {
				val += `<tr>
				    <td class="name">${item}</td>
				    <td class="btn-span">
				          <span class="edit">绑定</span>
				     </td>
				     </tr>
				`
			}
		})

	}
	$('.popup-wifi-info .table-main').html(val)
}

function getLevel(info) {
	let val = ''
	switch (info) {
		case 'TO_BE_IGNORED':
			val = '不集成';
			break
		case 'TO_BE_NOTICED':
			val = '不集成';
			break
		case 'TO_BE_RESPECTED':
			val = '部分';
			break
		case 'TO_BE_UTILIZED':
			val = '完全';
			break
	}
	return val
}

function getOrderList(arr) {
	let val = ''
	if (arr && arr.length) {
		arr.map(item => {
			val += `
            <div class="operate-details">
                <div>
                    ${item.workstation}
                    <span>(${item.text})</span>
                </div>
                   <img src="./img/line.png" alt="">
            </div>
            `
		})
		$('.operate-box .order-btn-box').show()
	} else {
		$('.operate-box .order-btn-box').hide()
	}
	$('.operate-box .order-main').html(val)
}

function isValidIP(ip) {
	var reg =
		/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/
	return reg.test(ip);
}

function toastText(val) {
	mui.toast(val, {
		duration: 2000,
		type: 'div'
	});
	setTimeout(function() {
		// 隐藏toast
		// plus.nativeUI.toast.hide();
	}, 2000 );
}

function getWifiInfo() {

	androidOpenWifi()
	// wifi
	let itemWifiSSID = localStorage.getItem('wifiSSID') || "",
		itemwifiPassword = localStorage.getItem('wifiPassword') || ""
	if ((wifiSSID || itemWifiSSID) && (wifiPassword || itemwifiPassword)) {
		androidWifiConnection(wifiSSID || itemWifiSSID, wifiPassword || itemwifiPassword, "wpa")
	}

	// if (wifiSSID && wifiPassword) {
	// 	androidWifiConnection(wifiSSID, wifiPassword, "wpa2"); //
	// 	// ping()
	// 	// window.location.reload()
	// }

}

function reloadWifi() {
	getWifiInfo()
}

$('.operate-box-main .show-img').click(function() {
	$('.operate-box-main ').hide()
})

let switchIndex = 0
$('.overall.show-img').click(function() {
	if (switchIndex) {
		$('.operate-box-main').show()
		switchIndex = 0
	} else {
		$('.operate-box-main').hide()
		switchIndex = 1
	}

})
// 微调、前进

function toRechargeWithType(url, msg) {
	$.ajax({
		url,
		contentType: "multipart/form-data",
		params: vehiclesName,
		type: "post",
		dataType: "json",
		success: (res) => {

			if (withTypeIndex) {
				toastText(msg)
				withTypeIndex = 0
			}
		},
		timeout: timeOut,
		error: () => {
			overTime()
		}
	})
}

function AutoScroll(obj) {
	$(obj).find("ul:first").animate({
		marginTop: "-24px"
	}, 1000, function() {
		$(this).css({
			marginTop: "0px"
		}).find("li:first").appendTo(this);
	});
}

function rollIng() {
	clearInterval(orderInterval)
	$('#orderList .news_li').html('')
	let data = [],
		val = ''
	getAllOrder().map(item=>{
		if(item.state == 5 || item.state == 'FINISHED'){

		}else{
			data.push(item)
		}
	})
	if (data && data.length) {
		data.map(item => {
			val += `
				<li>
					订单号：${item.name},执行车辆：${item.processingVehicle||'/'},状态：${getOrderState(item.state)}
				</li>
			`
		})
		$('#orderList .news_li').html(val)
		$('.no-order').hide()
		$('.an-order').show()
	} else {
		$('.no-order').show()
		$('.an-order').hide()
	}
	orderInterval = setInterval('AutoScroll("#orderList")', 3000,);
}
$('#orderList').click(function() {
	getOrderDetail()
})

function getOrderDetail() {
	$('.popup-order .table-main').html('')
	let val = ''
	let arr = []
	getAllOrder().map(item=>{
		if(item.state == 5 || item.state == 'FINISHED'){

		}else{
			arr.push(item)
		}
	})
	if (!!(arr && arr.length)) {
		arr.map(item => {
			val += `<tr>
	             <td class="name">${item.name}</td>
	             <td>${item.processingVehicle || '/'}</td>
	             <td>${item.intendedVehicle || '/'}</td>
	             <td>${item.destinations[0].locationName}</td>
				 <td>${getOrderState(item.state)}</td>
	             <td>${getChinese(item.destinations[0].operation)}</td>
	             <td class="btn-span">
	                  <span class="del">删除</span>
	             </td>
	             </tr>
	        `
		})
	}else{
		val = `<tr>
		             <td class="name"></td>
		             <td></td>
					  <td></td>
		             <td>暂无订单</td>
		             <td></td>
		             <td class="btn-span">
		             </td>
		             </tr>
		        `

	}

	$('.popup-order .table-main').html(val)
	$('.popup-order').show()
}
//订单删除
$('.popup-order .table-main').on('click', '.btn-span .del', function() {
	let name = $(this).parents('tr').children('.name').text(),
		id = ''

	var btnArray = ['删除', '取消'];
	mui.confirm('您确定删除此订单?', '', btnArray, function(e) {
		if (e.index == 0) {

			mui.showLoading("正在加载..", "div");
			// 确认退出触发事件http://localhost:55200/v1/transportOrders/TOrder-01HR3Z7K1SGE5J0KVGS8XPK5SA/withdrawal?immediate=true&disableVehicle=false
			$.ajax({
				url: `http://${ipValue}:55200/v1/transportOrders/${name}/withdrawal?immediate=true&disableVehicle=false`,
				contentType: "multipart/form-data",
				data: '',
				type: "post",
				async: !workInfo,
				dataType: "json",
				success: (res) => {
					mui.hideLoading();
					if (res.code == 200) {
						toastText('删除成功')
						getOrderDetail()
						rollIngOrder()
					} else {
						toastText(res.msg)

					}
				},
				timeout: timeOut,
				error: () => {
					overTime()
				}
			})
		} else {}
	})
})

function getOrderState(val) {

	let data = ''
	switch (val) {
		case 'RAW':
			data = '已初始化'
			break;
		case 'ACTIVE':
			data = '订单可被调度'
			break;
		case 'DISPATCHABLE':
			data = '订单在被调度'
			break;
		case 'BEING_PROCESSED':
			data = '订单执行中'
			break;
		case 'WITHDRAWN':
			data = '订单已从车辆中撤回'
			break;
		case 'FINISHED':
			data = '订单结束'
			break;
		case 'FAILED':
			data = '订单失败'
			break;
		case 'UNROUTABLE':
			data = '没有合适的路线'
			break;
		case '0':
			data = '已初始化'
			break;
		case 1:
			data = '订单可被调度'
			break;
		case 2:
			data = '订单在被调度'
			break;
		case 3:
			data = '订单执行中'
			break;
		case 4:
			data = '订单已从车辆中撤回'
			break;
		case 5:
			data = '订单结束'
			break;
		case 6:
			data = '订单失败'
			break;
		case 7:
			data = '没有合适的路线'
			break;
	}
	return data
}
